package run.bottle.urp.service.impl;

import org.springframework.stereotype.Service;
import run.bottle.urp.model.po.Role;
import run.bottle.urp.model.po.UserRole;
import run.bottle.urp.repository.RoleRepo;
import run.bottle.urp.repository.UserRepo;
import run.bottle.urp.repository.UserRoleRepo;
import run.bottle.urp.service.RoleService;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyc
 * @date 2022-03-25
 */
@Service
public class RoleServiceImpl implements RoleService {

    private final RoleRepo roleRepo;
    private final UserRoleRepo userRoleRepo;

    public RoleServiceImpl(RoleRepo roleRepo, UserRoleRepo userRoleRepo) {
        this.roleRepo = roleRepo;
        this.userRoleRepo = userRoleRepo;
    }

    @Override
    public Role saveRole(Role role) {
        return roleRepo.save(role);
    }

    @Override
    public List<Role> findRoleByUserId(Long userId) {
        List<UserRole> userRoles = userRoleRepo.findByUserId(userId);
        if (userRoles.size() > 0) {
            List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            return roleRepo.findByIdIn(roleIds);
        }
        return new ArrayList<Role>();
    }

    @Override
    public List<Role> findByIdIn(List<Long> ids) {
        return roleRepo.findByIdIn(ids);
    }
}
